<?php

class CL_Loader {

    private static $instance = NULL;
    private $out;

    private function CL_Loader() {
        $this->out = CL_Output::get_instance();
    }

    /**
     * @return CL_Loader
     */
    public static function get_instance() {
        if (self::$instance === NULL) {
            self::$instance = new CL_Loader();
        }
        return self::$instance;
    }

    public function library($library) {

        if (!file_exists(APPPATH . 'libraries/' . $library . '.php')) {
            show_error("Requested library does not exist.", "Loader Error");
        }

        require_once APPPATH . 'libraries/' . $library . '.php';
    }

    public function model($model) {

        if (!file_exists(APPPATH . 'models/' . $model . '.php')) {
            show_error("Requested model $model does not exist.", "Loader Error");
        }

        require_once APPPATH . 'models/' . $model . '.php';
    }

    public function view($view) {

        if (!file_exists(APPPATH . 'views/' . $view . '.php')) {
            show_error("Requested view does not exist.", "Loader Error");
        }

        foreach ($this->out->vars as $var => $value) {
            ${$var} = $value;
        }

        ob_start();
        include APPPATH . 'views/' . $view . '.php';
        $this->out->append(ob_get_contents());
        ob_clean();
    }

    public function page_view($view) {

        $view = strtolower($view);
        $contents = '';

        if (!file_exists(APPPATH . $view . '.php')) {
            show_error("Requested view $view.php does not exist.", "Page Error");
        }

        ob_start();

        if (file_exists(APPPATH . $view . '_control.php')) {
            include  APPPATH . $view . '_control.php';
        }

        include APPPATH . $view . '.php';
        $contents .= ob_get_contents();
        ob_clean();

        return $contents;
    }

    public function app_view($view) {

        if (!defined('APPNAME')) {
            show_error("Application name isn't defined", "App Error");
        }

        if (!file_exists(APPSPATH . APPNAME . '/views/' . $view . '.php')) {
            show_error("Requested application view does not exist.", "App Error");
        }

        foreach ($this->out->vars as $var => $value) {
            ${$var} = $value;
        }

        ob_start();
        include APPSPATH . APPNAME . '/views/' . $view . '.php';
        $this->out->append(ob_get_contents());
        ob_clean();
    }
}


/* End of file Loader.php */
/* Location: /system/libraries/Loader.php */